package zcw.com.lib_leet_code;

import zcw.com.lib_leet_code.bean.ListNode;
import zcw.com.lib_leet_code.util.Util;

/**
 * Created by 朱城委 on 2021/8/17.<br><br>
 *
 * 中等：交换链表中的节点
 */
public class Topic1721 {

    public static void main(String[] args) {
        Topic1721 instance = new Topic1721();

        int[] array = new int[] {1,2,3,4,5};
        ListNode head = Util.createList(array);
        Util.printList(instance.swapNodes(head, 2));

        array = new int[] {7,9,6,6,7,8,3,0,9,5};
        head = Util.createList(array);
        Util.printList(instance.swapNodes(head, 1));

        array = new int[] {1};
        head = Util.createList(array);
        Util.printList(instance.swapNodes(head, 1));

        array = new int[] {1,2};
        head = Util.createList(array);
        Util.printList(instance.swapNodes(head, 1));

        array = new int[] {1,2,3};
        head = Util.createList(array);
        Util.printList(instance.swapNodes(head, 2));
    }

    public ListNode swapNodes(ListNode head, int k) {

        ListNode index1 = head;
        ListNode low = head;
        ListNode fast = head;

        for(int i = 1; i < k; i++) {
            index1 = index1.next;
            fast = fast.next;
        }

        fast = fast.next;

        while (fast != null) {
            low = low.next;
            fast = fast.next;
        }

        int temp = index1.val;
        index1.val = low.val;
        low.val = temp;

        return head;
    }
}
